package com.lc.user.express.my;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.user.express.BaseFragment;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetMy;
import com.lc.user.express.httpserver.Net;
import com.lc.user.express.httpserver.PostHeadPic;
import com.lc.user.express.ordering.ManageUsedRouteActivity;
import com.lc.user.express.ordermanagement.OrderManagementFragment;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.PublicMethod;
import com.lc.user.express.utils.image.ImageManager;
import com.lc.user.express.view.SelectPicPopupWindow;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.yuntongxun.ecsdk.ECDevice;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.yun.YunAction;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by Administrator on 2016/2/29.  我的
 */
public class MyFragment extends BaseFragment {
    public static OnReFresh onReFresh = null;
    private MyFragment myFragment;
    private FragmentManager fragmentManager;
    FragmentTransaction transaction;
    public static TextView tv_login, tv_phone;//未登录  登陆后手机号
    public static SimpleDraweeView riv_head;//头像
    public static TextView tv_public;//退出登录
    private View view;
    private String servicePhone = "";//客服电话
    private SelectPicPopupWindow menuWindow;//上传
    private Uri photouri;

    private String picUrl;//加载头像url，主要用于避免修改头像后仍然显示原来缓存的头像


    @Override
    public View getContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        view = inflater.inflate(R.layout.fragment_my, container, false);
        setTitle("我的");
        initView(view);
       // getMyData();
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        getMyData();
    }

    private void initView(View v) {

        tv_login = (TextView) v.findViewById(R.id.tv_login);//登录
        tv_phone = (TextView) v.findViewById(R.id.tv_phone);//手机号
        riv_head = (SimpleDraweeView) v.findViewById(R.id.riv_head);//头像
        riv_head.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        ((LinearLayout) v.findViewById(R.id.my_accout)).setOnClickListener(this);//账户余额
        ((LinearLayout) v.findViewById(R.id.my_coupon)).setOnClickListener(this);//我的优惠券
        ((LinearLayout) v.findViewById(R.id.my_integral)).setOnClickListener(this);//我的积分
        ((LinearLayout) v.findViewById(R.id.my_route)).setOnClickListener(this);//我的常用路线
        ((LinearLayout) v.findViewById(R.id.my_fee_stardand)).setOnClickListener(this);//收费标准
        ((LinearLayout) v.findViewById(R.id.my_user_agreement)).setOnClickListener(this);//用户协议
        ((LinearLayout) v.findViewById(R.id.my_about)).setOnClickListener(this);//关于我们
        ((LinearLayout) v.findViewById(R.id.my_service)).setOnClickListener(this);//联系客服
        tv_public = ((TextView) v.findViewById(R.id.tv_public));//退出登录
        tv_public.setOnClickListener(this);

        initTopView();
        onReFresh = new OnReFresh() {
            @Override
            public void onRefresh() {
                initTopView();
                getMyData();
            }
        };

    }

    /**
     * 顶部手机号 头像
     */
    private void initTopView() {
        if (!AppContext.myPreferences.getIsLogin()) {
            ((TextView) view.findViewById(R.id.tv_balance)).setText("");
            ((TextView) view.findViewById(R.id.tv_coupon)).setText("");
            ((TextView) view.findViewById(R.id.tv_integral)).setText("");
            tv_login.setVisibility(View.VISIBLE);
            tv_phone.setVisibility(View.GONE);
            riv_head.setVisibility(View.GONE);
            tv_public.setVisibility(View.GONE);
        } else {
            tv_login.setVisibility(View.GONE);
            tv_phone.setVisibility(View.VISIBLE);
            riv_head.setVisibility(View.VISIBLE);
            tv_phone.setText(AppContext.myPreferences.getUserName());
            tv_public.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_login:
                show(LoginActivity.class);
                break;
            case R.id.my_accout:
                if (!AppContext.myPreferences.getIsLogin()) {
                    show(LoginActivity.class, LoginActivity.TYPE_LOGIN);
                } else {
                    show(AccountBalanceActivity.class);
                }
                break;
            case R.id.my_coupon:
                if (!AppContext.myPreferences.getIsLogin()) {
                    show(LoginActivity.class, LoginActivity.TYPE_LOGIN);
                } else {
                    show(MyCouponActivity.class);
                }
                break;
            case R.id.my_integral:
                if (!AppContext.myPreferences.getIsLogin()) {
                    show(LoginActivity.class, LoginActivity.TYPE_LOGIN);
                } else {
                    show(MyIntegralActivity.class);
                }
                break;
            case R.id.my_route:
                if (!AppContext.myPreferences.getIsLogin()) {
                    show(LoginActivity.class, LoginActivity.TYPE_LOGIN);
                } else {
                    show(ManageUsedRouteActivity.class);
                }
                break;
            case R.id.my_fee_stardand:
                show(MyStardandActivity.class);
                break;
            case R.id.my_user_agreement:
                show(MyUserAgreement.class);
                break;
            case R.id.my_about:
                show(MyAboutActivity.class);
                break;
            case R.id.my_service:
                new AffirmDialog(getActivity(), "正在为您联系168客服", "取消", "呼叫", R.style.MyDialog) {

                    @Override
                    protected void onYesClick() {

                        // TODO Auto-generated method stub
                        PublicMethod.callPhone(activity, servicePhone);

                    }
                }.show();
                break;
            case R.id.tv_public:

                if (!AppContext.myPreferences.getIsLogin()) {
                    GetToast.useString(getActivity(), "您还未登录");
                    return;
                }
                new AffirmDialog(getActivity(), "您确定要退出该账户吗？", "取消", "确认", R.style.MyDialog) {
                    @Override
                    protected void onYesClick() {
                        YunAction.getInstance().logout(getActivity(), new ECDevice.OnLogoutListener() {
                            @Override
                            public void onLogout() {
                                if (OrderManagementFragment.onRefreshOrderData != null) {
                                    OrderManagementFragment.onRefreshOrderData.onRefresh();
                                }
                                AppContext.myPreferences.setIsLogin(false);
                                AppContext.myPreferences.setUid("");
                                AppContext.myPreferences.setUserName("");
                                initTopView();
//                                JPushInterface.stopPush(getActivity());
                            }
                        });
                    }
                }.show();
                break;
            case R.id.riv_head:
                menuWindow = new SelectPicPopupWindow(activity, itemsOnClick, "上传照片");
                menuWindow.showAtLocation(view.findViewById(R.id.ll_container), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
        }
    }

    /**
     * 获得我的相关数据
     */
    private void getMyData() {
        new GetMy(AppContext.myPreferences.getUid(), new AsyCallBack<GetMy.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetMy.Info info) throws Exception {

                if (AppContext.myPreferences.getIsLogin()) {
                    ((TextView) view.findViewById(R.id.tv_balance)).setText(TextUtils.isEmpty(info.balance) ? "" : info.balance + "元");
                    ((TextView) view.findViewById(R.id.tv_coupon)).setText(TextUtils.isEmpty(info.coupon_number) ? "" : info.coupon_number + "张");
                    ((TextView) view.findViewById(R.id.tv_integral)).setText(info.integral);
                    servicePhone = info.telephone;
                    picUrl = Net.SERVER + info.picUrl;
                    ImageManager.from(activity).mMemoryCache.remove(picUrl);// 修改头像成功后清内存和sd卡缓存
                    ImageManager.from(activity).clearCache(picUrl, getActivity());
                    riv_head.setTag(null);
               //     ImageManager.from(getActivity()).displayImage(riv_head, picUrl, R.mipmap.head_default);

                    riv_head.setImageURI(Uri.parse(picUrl));
                    Log.d("000000000000000000000",picUrl);


                } else {
                    servicePhone = info.telephone;
                }

            }

        }).execute(activity);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    if (PublicMethod.isSdcardAvaiable()) {
                        String fileName = createFilename();
                        photouri = Uri.fromFile(new File(fileName));

                        Intent captureintent = new Intent("android.media.action.IMAGE_CAPTURE");
                        captureintent.putExtra(MediaStore.EXTRA_OUTPUT, photouri);
                        startActivityForResult(captureintent, 1);
                    } else {
                        GetToast.useString(getActivity(), "SD卡不可用");
                    }
                    break;
                case R.id.btn_pick_photo:
                    Intent intent = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, 0);
                    break;

                default:
                    break;
            }

        }

    };

    private String createFilename() {
        File file = new File(ImageManager.UPLOAD_PIC);
        if (!file.exists()) {
            file.mkdirs();// 创建文件夹
        }

        @SuppressWarnings("static-access")
        String fileName = ImageManager.UPLOAD_PIC
                + new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        return fileName;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != -1) {
            return;
        }
        if (requestCode == 0) {
            if (data != null) {
                photouri = data.getData();
                startPhotoZoom(photouri);
            }
        } else if (requestCode == 1) {
            if (null != photouri) {
                startPhotoZoom(photouri);
            }
        } else if (requestCode == 2) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Bitmap bitmap = bundle.getParcelable("data");
                upLoadHead(bitmap);
            }
        }
    }

    //裁剪图片方法实现
        private void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//设置裁剪
        intent.putExtra("aspectX", 1);//宽高的比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);//裁剪图片宽高
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    public String Bitmap2StrByBase64(Bitmap bit) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        byte[] bytes = bos.toByteArray();

        return Base64.encodeToString(bytes, Base64.DEFAULT);

    }

    /**
     * @param bitmap 上传头像
     */
    private void upLoadHead(final Bitmap bitmap) {
        new PostHeadPic(AppContext.myPreferences.getUid(), Bitmap2StrByBase64(bitmap), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object o) throws Exception {

                riv_head.setImageBitmap(bitmap);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                GetToast.useString(activity, toast);
            }
        }).execute(activity);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onReFresh = null;
    }

    public interface OnReFresh {
        void onRefresh();
    }

}
